<template>
  <div class="app">
    <div class="counter-left">
      <table border="1" cellspacing="0">
        <thead>
          <tr>
            <th>编号</th>
            <th>科目</th>
            <th>分数</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="data.length > 0">
          <tr v-for="(item, index) in data" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.kemu }}</td>
            <td :class="item.cj < 60 ? 'bjgfs' : ''">{{ item.cj }}</td>
            <td>
              <a href="javascript:void(0);" @click="del(item.id)">删除</a>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="4">暂无数据</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="4">总分：{{ zf }} 平均分：{{ pjf }}</td>
          </tr>
        </tfoot>
      </table>
      <div class="counter-right">
        <div class="box-container">
          <div class="box">
            <label for=""> 科目：</label>
            <input type="text" placeholder="请输入科目" v-model="kemus" />
          </div>
          <div class="box">
            <label for=""> 分数：</label>
            <input
              type="text"
              placeholder="请输入分数"
              v-model.number="fenshus"
            />
          </div>
          <button type="submit" @click="add()">添加</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";

const data = ref([
  { id: 1, kemu: "语文", cj: 46 },
  { id: 2, kemu: "英语", cj: 80 },
  { id: 3, kemu: "数学", cj: 100 },
]);
let kemus = ref("");
let fenshus = ref();

const add = () => {
  if (!kemus.value) {
    alert("请输入科目");
    return;
  }
  if (typeof fenshus.value !== "number") {
    alert("请输入正确的分数");
    return;
  }
  data.value.push({
    id: +new Date(),
    kemu: kemus.value,
    cj: fenshus.value,
  });

  kemus.value = "";
  fenshus.value = "";
};
const del = (id: number) => {
  data.value = data.value.filter((item) => item.id !== id);
};

const zf = computed(() => {
  return data.value.reduce((item, cjs) => item + cjs.cj, 0);
});

const pjf = computed(() => {
  return (zf.value / data.value.length || 0).toFixed(2);
});
</script>

<style lang="scss" scoped>
.app {
  width: 100%;
  .counter-left {
    gap: 80px;
    margin: 100px auto;
    justify-content: center;
    display: flex;
    flex-direction: row;
    table {
      width: 600px;
      text-align: center;
      tbody {
        .bjgfs {
          color: red;
        }
      }
    }
    .counter-right {
      width: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .box-container {
        display: flex;
        flex-direction: column;
        gap: 10px; // Add some space between boxes
        button {
          width: 50px;
        }
      }
    }
  }
}
</style>
